﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Logging;
using ServiceStack.Logging.Log4Net;
using g42.Dto;
using g42.Authentication.NH;
using g42.ServiceConsumer;
using g42.ServiceProvider;

namespace g42.dev.console
{
  class Program
  {
    static void WaitForSelection(ServCons sc, ServProv sp)
    {
      Boolean DoClose = false;
      while (!DoClose)
      {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("press a key:");
        Console.WriteLine("r: rebuild database");
        Console.WriteLine("t: create testdata");
        Console.WriteLine("s: sample service call");
        Console.WriteLine("any other key: close");
        ConsoleKeyInfo selection = Console.ReadKey(); // Auf Zeicheneingabe warten
        Console.Write("\b"); // gedrücktes Zeichen vom Bildschirm entfernen
        Console.ForegroundColor = ConsoleColor.Yellow;

        switch (selection.KeyChar)
        {
          // Rebuild
          case 'r':
            Console.WriteLine("rebuilding database and restart ServiceProvider...");
            try
            {
              sp.Stop();
              sp.Start(true); // true: DatabaseSchema neu erstellen
            }
            catch (Exception E)
            {
              Console.WriteLine(E.Message);
            }
            Console.WriteLine("done");
            break;

          // Testdaten
          case 't':
            Console.WriteLine("Creating testdata...");
            try
            {
              sc.CreateTestData();
            }
            catch (Exception E)
            {
              Console.WriteLine(E.Message);
            }
            Console.WriteLine("done");
            break;

          // SampleService
          case 's': 
            {
              Console.WriteLine("calling sample service...");
              try
              {


                /*
                var authResponse = client.Send<AuthResponse>(new Auth
                {
                  provider = CredentialsAuthProvider.Name,
                  UserName = "user",
                  Password = "p@55word",
                  RememberMe = true,  //important tell client to retain permanent cookies
                });

                var request = new Secured { Name = "test" };
                var response = client.Send<SecureResponse>(request); 
                */
                // http://stackoverflow.com/questions/13787324/user-authentication-when-consuming-a-rest-webservice-with-servicestack
                //var authResponse = sc.ServiceClient.Send<UserAuthPersistenceDto>(new UserAuth             {             });
                //UserAuthMap ua = sc.ServiceClient.Send<

                Sample s = sc.ServiceClient.Post(new Sample { Nr = "1", Bezeichnung = "auth test" });
                Console.WriteLine("result = " + s.Id.ToString());
              }
              catch (Exception E)
              {
                Console.WriteLine(E.Message);
              }
              break;
            }

          // Beenden
          default:
            {
              Console.WriteLine("closing app...");
              DoClose = true;
              break;
            }
        }

        Console.ResetColor();
      }
    }

    static void Main(string[] args)
    {
      try
      {
        // Als erstes logger starten
        LogManager.LogFactory = new Log4NetFactory(true);
        ILog log;
        log = LogManager.GetLogger("g42.dev-console");
        log.Info("start");

        // das läuft im Server
        ServProv sp = new ServProv();
        sp.Start(false); // true: DatabaseSchema neu erstellen

        // Das läuft im client
        ServCons sc = new ServCons();
        sc.Start();

        WaitForSelection(sc, sp);

        /*

        Mandant md = sc.ServiceClient.Post(new Mandant { Nr = "1", Name = "default" });
        log.Info("Default Mandant created: Id=" + md.Id + ", Name=" + md.Name);

        Strasse str = sc.ServiceClient.Post(new Strasse { Nr = "1", Name = "Hauptstr.", Laenge = 1800 });
        log.Info("Strasse created: Id=" + str.Id + ", Nr=" + str.Nr + ", Name=" + str.Name + ", Laenge=" + str.Laenge.ToString());

        Adresse adr = sc.ServiceClient.Post(new Adresse { Nr = "2", Strasse = str, HauseNr1 = 42 });
        log.Info("Adresse created: Id=" + adr.Id + ", Nr=" + adr.Nr + ", HouseNr1=" + adr.HauseNr1);

        // TestPerson anlegen
        Mandant m = sc.ServiceClient.Get(new Mandant());
        Adresse a = sc.ServiceClient.Get(new Adresse());
        Person p = new Person();
        p.Nr = "3";
        p.Md = m;
        p.Adresse = a;
        p.Vorname = "Fritzchen";
        p.Name = "Testmeier";
        sc.ServiceClient.Post(p);
        // Alle Personen auslesen
        List<Person> kl = sc.ServiceClient.Get(new PersonList() { Filter = "e" });
        foreach (Person k1 in kl)
        {
          log.Info("Person ID=" + k1.Id.ToString() + ", Vorname=" + k1.Vorname + ", Name=" + k1.Name + ", Mandant.Name=" + k1.Md.Name);
        }

         */
      }
      catch (Exception E)
      {
        Console.WriteLine(E.Message);
        Console.ReadKey();
      }
    }
    
  }
}
